package com.bawei.hgshop.controller;

import java.util.List;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bawei.hgshop.entity.Category;
import com.bawei.hgshop.entity.MsgResult;
import com.bawei.hgshop.service.CategoryService;

/**
 * 分类
 * @时间  2021-1-13  10:26:31
 *
 */
@Controller
@RequestMapping("category")
public class CategoryController {
	
	/**
	 * 注入kafka 修改分类的时候发下发送消息给前台
	 */
	@Autowired
	KafkaTemplate<String, String> kfkTemplate;
	
	//分类的管理
	@Reference
	CategoryService catService;
	
	
	/**
	 * 发送kfka 消息
	 */
	private void sendKfkMessage(String key,String content) {
		kfkTemplate.send("hgshop", key, content);	
	}
	/**
	 * 列表
	 * @return
	 */
	@RequestMapping("list")
	public String list() {
		
		return "category/list";
	}
	
	/**、
	 * 
	 * @return
	 */
	@RequestMapping("treeData")
	@ResponseBody
	public MsgResult treeData() {
		
		List<Category> cats =  catService.tree();
		
		return new MsgResult(0,"",cats);
	}
	
	/**
	 * 
	 * @param cat
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public MsgResult update(Category cat) {
		
		int update = catService.update(cat);
		// 发送kfka 消息
		sendKfkMessage("cat","update cat");
		
		return new MsgResult(0, "", null);
		
	}
	
	/**
	 * 
	 * @param cat
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public MsgResult add(Category cat) {
		
		int add = catService.add(cat);
		// 发送kfka 消息
		sendKfkMessage("cat","add cat");
		
		return new MsgResult(0, "", null);
		
	}
	
	@RequestMapping("del")
	@ResponseBody
	public MsgResult del(int id) {
		
		int del = catService.delById(id);
		if(del<0) {
			return new MsgResult(2, "存在子节点不能删除", null);
		}else if(del == 0) {
			return new MsgResult(3, "删除失败，请稍后再试或与管理员联系", null);
		}else {
			// 发送kfka 消息
			sendKfkMessage("cat","del cat");
			return new MsgResult(0, "ok", null);
		}
		
	}
	
	

}
